const { User, Invitation, Resume } = require('../models');
const { Op } = require('sequelize');
const QRCode = require('qrcode');
const path = require('path');
const { exportResumesToCsv } = require('../utils/exportData');

// 获取所有用户
exports.getUsers = async (req, res, next) => {
  try {
    const users = await User.findAll({
      attributes: ['id', 'username', 'name', 'role', 'lastLogin', 'createdAt', 'updatedAt']
    });
    
    res.json({
      success: true,
      data: users
    });
  } catch (error) {
    next(error);
  }
};

// 创建用户
exports.createUser = async (req, res, next) => {
  try {
    const { username, password, name, role } = req.body;
    
    // 验证请求体
    if (!username || !password || !name) {
      return res.status(400).json({
        success: false,
        message: '请提供用户名、密码和姓名'
      });
    }
    
    // 检查用户名是否已存在
    const existingUser = await User.findOne({ where: { username } });
    
    if (existingUser) {
      return res.status(400).json({
        success: false,
        message: '用户名已存在'
      });
    }
    
    // 创建用户
    const user = await User.create({
      username,
      password,
      name,
      role: role || 'user'
    });
    
    res.status(201).json({
      success: true,
      message: '用户创建成功',
      data: {
        id: user.id,
        username: user.username,
        name: user.name,
        role: user.role
      }
    });
  } catch (error) {
    next(error);
  }
};

// 更新用户
exports.updateUser = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { name, role } = req.body;
    
    // 查找用户
    const user = await User.findByPk(id);
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 更新用户
    await user.update({
      name: name || user.name,
      role: role || user.role
    });
    
    res.json({
      success: true,
      message: '用户更新成功',
      data: {
        id: user.id,
        username: user.username,
        name: user.name,
        role: user.role
      }
    });
  } catch (error) {
    next(error);
  }
};

// 删除用户
exports.deleteUser = async (req, res, next) => {
  try {
    const { id } = req.params;
    
    // 不允许删除自己
    if (parseInt(id) === req.user.id) {
      return res.status(400).json({
        success: false,
        message: '不能删除当前登录的用户'
      });
    }
    
    // 查找用户
    const user = await User.findByPk(id);
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 删除用户
    await user.destroy();
    
    res.json({
      success: true,
      message: '用户删除成功'
    });
  } catch (error) {
    next(error);
  }
};

// 创建邀请链接
exports.createInvitation = async (req, res, next) => {
  try {
    const { title, description, position, department, expiresAt, maxSubmissions } = req.body;
    
    // 验证请求体
    if (!title || !position) {
      return res.status(400).json({
        success: false,
        message: '请提供标题和职位'
      });
    }
    
    // 创建邀请链接
    const invitation = await Invitation.create({
      title,
      description,
      position,
      department,
      createdBy: req.user.id,
      expiresAt: expiresAt ? new Date(expiresAt) : null,
      maxSubmissions: maxSubmissions || 0
    });
    
    // 生成二维码
    const invitationUrl = `${req.protocol}://${req.get('host')}/resume/${invitation.code}`;
    const qrCode = await QRCode.toDataURL(invitationUrl);
    
    res.status(201).json({
      success: true,
      message: '邀请链接创建成功',
      data: {
        invitation,
        url: invitationUrl,
        qrCode
      }
    });
  } catch (error) {
    next(error);
  }
};

// 获取所有邀请链接
exports.getInvitations = async (req, res, next) => {
  try {
    const invitations = await Invitation.findAll({
      include: [
        {
          model: User,
          attributes: ['id', 'username', 'name']
        }
      ],
      order: [['createdAt', 'DESC']]
    });
    
    res.json({
      success: true,
      data: invitations
    });
  } catch (error) {
    next(error);
  }
};

// 获取单个邀请链接
exports.getInvitation = async (req, res, next) => {
  try {
    const { id } = req.params;
    
    const invitation = await Invitation.findByPk(id, {
      include: [
        {
          model: User,
          attributes: ['id', 'username', 'name']
        },
        {
          model: Resume,
          attributes: [
            'id', 'link_token', 'name', 'nickname', 'phone', 'wechat', 
            'gender', 'age', 'weight', 'education', 'hobbies', 
            'special_skills', 'can_drink', 'can_livestream', 
            'preferred_shift', 'game_experience', 'self_introduction', 
            'photos', 'work_experience', 'weekly_availability', 
            'status', 'invitation_id', 'created_at', 'updated_at'
          ]
        }
      ]
    });
    
    if (!invitation) {
      return res.status(404).json({
        success: false,
        message: '邀请链接不存在'
      });
    }
    
    // 生成二维码
    const invitationUrl = `${req.protocol}://${req.get('host')}/resume/${invitation.code}`;
    const qrCode = await QRCode.toDataURL(invitationUrl);
    
    res.json({
      success: true,
      data: {
        invitation,
        url: invitationUrl,
        qrCode
      }
    });
  } catch (error) {
    next(error);
  }
};

// 更新邀请链接
exports.updateInvitation = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { title, description, position, department, expiresAt, isActive, maxSubmissions } = req.body;
    
    // 查找邀请链接
    const invitation = await Invitation.findByPk(id);
    
    if (!invitation) {
      return res.status(404).json({
        success: false,
        message: '邀请链接不存在'
      });
    }
    
    // 更新邀请链接
    await invitation.update({
      title: title || invitation.title,
      description: description !== undefined ? description : invitation.description,
      position: position || invitation.position,
      department: department !== undefined ? department : invitation.department,
      expiresAt: expiresAt ? new Date(expiresAt) : invitation.expiresAt,
      isActive: isActive !== undefined ? isActive : invitation.isActive,
      maxSubmissions: maxSubmissions !== undefined ? maxSubmissions : invitation.maxSubmissions
    });
    
    res.json({
      success: true,
      message: '邀请链接更新成功',
      data: invitation
    });
  } catch (error) {
    next(error);
  }
};

// 删除邀请链接
exports.deleteInvitation = async (req, res, next) => {
  try {
    const { id } = req.params;
    
    // 查找邀请链接
    const invitation = await Invitation.findByPk(id);
    
    if (!invitation) {
      return res.status(404).json({
        success: false,
        message: '邀请链接不存在'
      });
    }
    
    // 删除邀请链接
    await invitation.destroy();
    
    res.json({
      success: true,
      message: '邀请链接删除成功'
    });
  } catch (error) {
    next(error);
  }
};

// 获取所有简历
exports.getResumes = async (req, res, next) => {
  try {
    const { status, invitationId, page = 1, pageSize = 10, name = '' } = req.query;
    
    // 构建查询条件
    const where = {};
    
    if (status) {
      where.status = status;
    }
    
    if (invitationId) {
      where.invitation_id = invitationId;
    }
    
    if (name) {
      where.name = {
        [Op.like]: `%${name}%`
      };
    }
    
    // 分页参数
    const offset = (page - 1) * pageSize;
    const limit = parseInt(pageSize);
    
    // 查询简历总数
    const total = await Resume.count({ where });
    
    // 查询简历数据
    const resumes = await Resume.findAll({
      where,
      include: [
        {
          model: Invitation,
          attributes: ['id', 'code', 'title', 'position', 'department']
        }
      ],
      // 确保返回所有需要的字段
      attributes: [
        'id', 'link_token', 'name', 'nickname', 'phone', 'wechat', 
        'gender', 'age', 'weight', 'education', 'hobbies', 
        'special_skills', 'can_drink', 'can_livestream', 'accept_night_shift',
        'preferred_shift', 'game_experience', 'self_introduction', 
        'photos', 'work_experience', 'weekly_availability', 
        'status', 'invitation_id', 'created_at', 'updated_at'
      ],
      order: [['created_at', 'DESC']],
      offset,
      limit
    });
    
    res.json({
      success: true,
      data: {
        total,
        page: parseInt(page),
        pageSize: limit,
        list: resumes
      }
    });
  } catch (error) {
    next(error);
  }
};

// 获取单个简历
exports.getResume = async (req, res, next) => {
  try {
    const { id } = req.params;
    
    const resume = await Resume.findByPk(id, {
      include: [
        {
          model: Invitation,
          attributes: ['id', 'code', 'title', 'position', 'department']
        }
      ],
      // 确保返回所有需要的字段
      attributes: [
        'id', 'link_token', 'name', 'nickname', 'phone', 'wechat', 
        'gender', 'age', 'weight', 'education', 'hobbies', 
        'special_skills', 'can_drink', 'can_livestream', 'accept_night_shift',
        'preferred_shift', 'game_experience', 'self_introduction', 
        'photos', 'work_experience', 'weekly_availability', 
        'status', 'invitation_id', 'created_at', 'updated_at'
      ]
    });
    
    if (!resume) {
      return res.status(404).json({
        success: false,
        message: '简历不存在'
      });
    }
    
    res.json({
      success: true,
      data: resume
    });
  } catch (error) {
    next(error);
  }
};

// 更新简历状态
exports.updateResumeStatus = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    
    // 验证请求体
    if (!status) {
      return res.status(400).json({
        success: false,
        message: '请提供状态'
      });
    }
    
    // 查找简历
    const resume = await Resume.findByPk(id);
    
    if (!resume) {
      return res.status(404).json({
        success: false,
        message: '简历不存在'
      });
    }
    
    // 更新简历状态
    await resume.update({
      status
    });
    
    res.json({
      success: true,
      message: '简历状态更新成功',
      data: resume
    });
  } catch (error) {
    next(error);
  }
};

// 删除简历
exports.deleteResume = async (req, res, next) => {
  try {
    const { id } = req.params;
    
    // 查找简历
    const resume = await Resume.findByPk(id);
    
    if (!resume) {
      return res.status(404).json({
        success: false,
        message: '简历不存在'
      });
    }
    
    // 删除简历
    await resume.destroy();
    
    res.json({
      success: true,
      message: '简历删除成功'
    });
  } catch (error) {
    next(error);
  }
};

// 导出简历
exports.exportResumes = async (req, res, next) => {
  try {
    const { invitationId, status } = req.query;
    
    // 构建查询条件
    const where = {};
    
    if (status) {
      where.status = status;
    }
    
    if (invitationId) {
      where.invitation_id = invitationId;
    }
    
    // 查询简历数据
    const resumes = await Resume.findAll({
      where,
      include: [
        {
          model: Invitation,
          attributes: ['id', 'code', 'title', 'position', 'department']
        }
      ],
      // 确保返回所有需要的字段
      attributes: [
        'id', 'link_token', 'name', 'nickname', 'phone', 'wechat', 
        'gender', 'age', 'weight', 'education', 'hobbies', 
        'special_skills', 'can_drink', 'can_livestream', 'accept_night_shift',
        'preferred_shift', 'game_experience', 'self_introduction', 
        'photos', 'work_experience', 'weekly_availability', 
        'status', 'invitation_id', 'created_at', 'updated_at'
      ],
      order: [['created_at', 'DESC']]
    });
    
    if (resumes.length === 0) {
      return res.status(404).json({
        success: false,
        message: '没有找到符合条件的简历'
      });
    }
    
    // 处理数据，将复杂对象转为可导出的格式
    const processedResumes = resumes.map(resume => {
      const data = { ...resume.dataValues };
      
      // 添加邀请信息
      if (resume.Invitation) {
        data.invitationTitle = resume.Invitation.title;
        data.position = resume.Invitation.position;
        data.department = resume.Invitation.department;
      }
      
      // 处理复杂字段
      if (data.photos && Array.isArray(data.photos)) {
        data.photos = data.photos.join(', ');
      }
      
      if (data.work_experience && Array.isArray(data.work_experience)) {
        data.work_experience = data.work_experience.map(exp => 
          `${exp.company} - ${exp.position} (${exp.startDate} ~ ${exp.endDate})`
        ).join('; ');
      }
      
      // 格式化日期
      if (data.created_at) {
        data.created_at = new Date(data.created_at).toLocaleString('zh-CN');
      }
      
      if (data.updated_at) {
        data.updated_at = new Date(data.updated_at).toLocaleString('zh-CN');
      }
      
      // 转换布尔值和枚举值为可读文本
      data.can_drink = data.can_drink === 'yes' ? '可以' : '不可以';
      data.can_livestream = data.can_livestream === 'yes' ? '可以' : '不可以';
      data.accept_night_shift = data.accept_night_shift === 'yes' ? '可以' : '不可以';
      
      if (data.preferred_shift === 'day') {
        data.preferred_shift = '早班';
      } else if (data.preferred_shift === 'night') {
        data.preferred_shift = '晚班';
      }
      
      if (data.gender === 'male') {
        data.gender = '男';
      } else if (data.gender === 'female') {
        data.gender = '女';
      } else if (data.gender === 'other') {
        data.gender = '其他';
      }
      
      if (data.game_experience === 'none') {
        data.game_experience = '完全不了解';
      } else if (data.game_experience === 'basic') {
        data.game_experience = '略有了解';
      } else if (data.game_experience === 'familiar') {
        data.game_experience = '比较熟悉';
      } else if (data.game_experience === 'expert') {
        data.game_experience = '非常熟悉';
      }
      
      if (data.status === 'pending') {
        data.status = '待审核';
      } else if (data.status === 'approved') {
        data.status = '已通过';
      } else if (data.status === 'rejected') {
        data.status = '已拒绝';
      }
      
      return data;
    });
    
    // 设置响应头，告诉浏览器这是一个Excel文件
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename=resumes_${Date.now()}.xlsx`);
    
    // 直接返回处理后的数据，前端会处理为Excel
    res.json({
      success: true,
      data: processedResumes
    });
  } catch (error) {
    next(error);
  }
};

// 获取统计数据
exports.getStatistics = async (req, res, next) => {
  try {
    // 获取当前日期
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    // 查询总简历数
    const totalApplicants = await Resume.count();
    
    // 查询今日新增简历数
    const todayApplicants = await Resume.count({
      where: {
        created_at: {
          [Op.gte]: today
        }
      }
    });
    
    // 查询有效链接数（未过期且状态为激活的）
    const activeLinks = await Invitation.count({
      where: {
        is_active: true,
        expires_at: {
          [Op.or]: [
            { [Op.gt]: new Date() },
            { [Op.eq]: null }
          ]
        }
      }
    });
    
    res.json({
      success: true,
      data: {
        totalApplicants,
        todayApplicants,
        activeLinks
      }
    });
  } catch (error) {
    next(error);
  }
};

// 获取最近简历
exports.getRecentApplicants = async (req, res, next) => {
  try {
    // 获取最近5条简历
    const recentApplicants = await Resume.findAll({
      attributes: ['id', 'name', 'gender', 'education', 'created_at'],
      order: [['created_at', 'DESC']],
      limit: 5
    });
    
    res.json({
      success: true,
      data: recentApplicants
    });
  } catch (error) {
    next(error);
  }
}; 